#include <stdio.h>
#include <stdlib.h>
#include "h/list.h"

static void CopyToNode(Item, Node *);
//static void traverseDesc(const Node *, ListItemCall);

void InitializeList(List * pl)
{
    pl->head = NULL;
    pl->tail = NULL;
    pl->size = 0;
}

bool ListIsEmpty(const List * pl)
{
    return pl->head == NULL;
}

bool ListIsFull()
{
    bool is_full = false;
    Node * pt = malloc(sizeof(Node));

    if (NULL == pt)
        is_full = true;
    else
        free(pt);

    return is_full;
}

unsigned ListItemCount(const List * pl)
{
    return pl->size;
}

bool AddItem(Item item, List * pl)
{
    Node * new = malloc(sizeof(Node));

    if (NULL == new)
        return false;

    CopyToNode(item, new);
    new->next = new->prev = NULL;

    if (NULL == pl->head)
    {
        pl->head = new;
        pl->tail = new;
    }
    else
    {
        new->prev = pl->tail;
        pl->tail->next = new;
        pl->tail = new;
    }

    ++pl->size;

    return true;
}

void Traverse(const List * pl, ListItemCall call)
{
    Node * curr = pl->head;
    while (curr != NULL) {
        call(&curr->item);
        curr = curr->next;
    }
}

void TraverseReverse(const List * pl, ListItemCall call)
{
    Node * curr = pl->tail;
    while (curr != NULL)
    {
        (*call)(&curr->item);
        curr = curr->prev;
    }
}

//使用递归实现单链表的递归
//static void traverseDesc(const Node * pn, ListItemCall call)
//{
//    if (pn->next != NULL)
//        traverseDesc(pn->next, call);
//
//    (*call)(&pn->item);
//}

void EmptyTheList(List * pl)
{
    Node * curr = pl->head;

    while (curr != NULL) {
       pl->head = pl->head->next;
       free(curr);
       curr = pl->head;
    }

    pl->tail = NULL;
    pl->size = 0;
}

static void CopyToNode(Item item, Node * node)
{
    node->item = item;
}

